package com.leyou.auth.web;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.util.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@EnableConfigurationProperties(JwtProperties.class)
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties props;

    @PostMapping("login")
    public ResponseEntity<Void> login(
            @RequestParam("username") String username, @RequestParam("password") String password,
            HttpServletRequest request, HttpServletResponse response
    ) {
        String token = authService.login(username, password);

        // 写入 cookie
        CookieUtils.setCookie(request, response, props.getCookieName(),
                token, -1);

        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 校验用户登录状态
     * @param token
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(
            @CookieValue("LY_TOKEN") String token,
            HttpServletRequest request, HttpServletResponse response
    ) {
        // 是否登录
        if (StringUtils.isBlank(token)) {
            // 未登录
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        // 解析 token
        try {
            UserInfo info = JwtUtils.getInfoFromToken(token, props.getPublicKey());

            // 刷新 token
            String newToken = JwtUtils.generateToken(info, props.getPrivateKey(), props.getExpire());

            // 写入 cookie
            CookieUtils.setCookie(request, response, props.getCookieName(),
                    token, -1);

            // 已登录，返回用户信息
            return ResponseEntity.ok(info);
        } catch (Exception e) {
            // token 过期 / 被篡改
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }
}
